/*****************************************************************************
* Project:
* All project
* Copyright(C) 2020-2021 Shenju Co.Ltd, All rights reserved.
* Description:
* All code is genrated by yangyang
* Author:
* yangyang
****************************************************************************/
#include "oal_event.h"

#include <Windows.h>

OAL_HANDLE OAL_event_create()
{
	int i;
	HANDLE *hEvents = (HANDLE*)malloc(sizeof(HANDLE) * 8);
	for (i = 0; i < 8; i++) {
		hEvents[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
	}
	return (OAL_HANDLE)hEvents;
}

uint8_t OAL_event_wait(OAL_HANDLE h, uint8_t bits, uint32_t wait_milliseconds)
{
	int i;
	int j = 0;
	uint8_t ret = 0;
	HANDLE* hEvents = (HANDLE*)h;
	HANDLE need_events[8];
	int nIndex;

	for (i = 0; i < 8; i++) {
		if (bits & (1 << i)) {
			need_events[j++] = hEvents[i];
		}
	}

	nIndex = WaitForMultipleObjects(j, need_events, TRUE, wait_milliseconds);
	if (WAIT_TIMEOUT == nIndex) return 0;
	if(nIndex >= WAIT_OBJECT_0)
		ret = bits;
	return ret;
}

uint8_t OAL_event_wait_clear(OAL_HANDLE h, uint8_t bits, uint32_t wait_milliseconds)
{
	int i;
	HANDLE* hEvents = (HANDLE*)h;
	uint8_t ret = OAL_event_wait(h, bits, wait_milliseconds);
	for (i = 0; i < 8; i++) {
		if (ret & (1 << i)) {
			ResetEvent(hEvents[i]);
		}
	}
	return ret;
}

uint8_t OAL_event_wait_any(OAL_HANDLE h, uint8_t bits, uint32_t wait_milliseconds)
{
	HANDLE* hEvents = (HANDLE*)h;
	HANDLE need_events[8];
	int i, k;
	int j = 0;
	uint8_t ret = 0;
	int nIndex;

	for (i = 0; i < 8; i++) {
		if (bits & (1 << i)) {
			need_events[j++] = hEvents[i];
		}
	}

	nIndex = WaitForMultipleObjects(j, need_events, FALSE, wait_milliseconds);
	if (WAIT_TIMEOUT == nIndex) return 0;
	if (nIndex >= WAIT_OBJECT_0) {
		for (i = 0; i < j; i++) {
			if (i == (int)(nIndex - WAIT_OBJECT_0))
				for (k = 0; k < 8; k++) {
					if (need_events[i] == hEvents[k])
						ret |= (1 << k);
				}
		}
	}
	return ret;
}

uint8_t OAL_event_wait_any_clear(OAL_HANDLE h, uint8_t bits, uint32_t wait_milliseconds)
{
	int i;
	HANDLE* hEvents = (HANDLE*)h;
	uint8_t ret = OAL_event_wait_any(h, bits, wait_milliseconds);
	for (i = 0; i < 8; i++) {
		if (ret & (1 << i)) {
			ResetEvent(hEvents[i]);
		}
	}
	return ret;
}

void OAL_event_set(OAL_HANDLE h, uint8_t bits)
{
	int i;
	HANDLE* hEvents = (HANDLE*)h;
	for (i = 0; i < 8; i++) {
		if (bits & (1 << i)) {
			SetEvent(hEvents[i]);
		}
	}
}

void OAL_event_clear(OAL_HANDLE h, uint8_t bits)
{
	int i;
	HANDLE* hEvents = (HANDLE*)h;
	for (i = 0; i < 8; i++) {
		if (bits & (1 << i)) {
			ResetEvent(hEvents[i]);
		}
	}
}

void OAL_event_destroy(OAL_HANDLE h)
{
	int i;
	HANDLE* hEvents = (HANDLE*)h;
	for (i = 0; i < 8; i++) {
		CloseHandle(hEvents[i]);
	}
	free(h);
}
